import { useState, useRef, useEffect, useMemo } from "react";
import { FolderS, FolderName, FodlerInput } from "./styled";
import { useNavigate } from "react-router-dom";
import { getRows } from "@/utils/func";
import dataManager from "@/utils/dataManager";
import indexedDBManager from "@/utils/indexedDB";
import { message } from "antd";
import { BLOG_ICON_TYPE, FOLDER_ICON_TYPE, IFRAME_ICON_TYPE, TEXT_ICON_TYPE } from "@/contains/iconTypeEnum";


const Folder = ({
  info: { uid, fid, x, y, name, iconType, iconUrl, iframeUrl, iframeColor, fatherNode },
  isFocus,
  isHover,
  isStatic,
  isRename,
  folderHandler,
  onDragStart,
  onDragEnd,
  onMouseOver,
  state: { folderData, isNewBuild, barIconData, iframeList },
  dispatch,
  onMouseOut,
}) => {
  const [filename, setFilename] = useState(name);
  const [zIndex, setZIndex] = useState(1);
  const folderNode = useRef(null);
  const navigate = useNavigate();
  const changeValueName = (e) => {
    setFilename(e.target.value);
  };

  const textareaNode = useRef(null);

  useEffect(() => {
    if (isRename) {
      textareaNode.current.focus();
      textareaNode.current.select();
    }
  }, [isRename]);

  // 重命名
  const updateFileName = async (e) => {
    // 没有改变
    if (filename === name) return;

    // 名字为空时
    if (e.target.value === "") {
      message.warn("名字不能为空！");
      setFilename(name); // 设置最近一次不为空的值
      return;
    }

    // 找到名字一样的文件夹时
    if (
      folderData.find(
        (item) => item.fid !== fid && item.name === e.target.value
      )
    ) {
      message.warn("重命名重名！");
      setFilename(name);
      return;
    }

    try {
      // 更新数据库数据
      await indexedDBManager.updateFolder(fid, { name: e.target.value });

      // 更新本地状态
      const updatedFolderData = folderData.map(item =>
        item.fid === fid ? { ...item, name: e.target.value } : item
      );

      dispatch({
        type: "setState",
        payload: {
          folderData: updatedFolderData,
        },
      });
    } catch (error) {
      message.error("重命名失败");
      setFilename(name);
    }
  };

  const addFilehandle = async (e) => {
    // 名字为空时
    if (e.target.value === "") {
      message.warn("名字不能为空！");
      setFilename(name); // 设置最近一次不为空的值
      return;
    }

    // 找到名字一样的文件夹时
    if (
      folderData.find(
        (item) =>
          item.fid !== fid &&
          item.name === e.target.value &&
          item.iconType === iconType
      )
    ) {
      dispatch({
        type: "setState",
        payload: {
          isTipsModelVisiable: true,
          modelType: "newBuild",
          modelTitle: "确认替换文件",
          modelContent: "是否将第一个文件和第二个文件合并",
        },
      });
      return;
    }

    try {
      const currentUser = await dataManager.getCurrentUser();
      if (!currentUser) throw new Error('未登录');

      const folder = folderData[folderData.length - 1];
      folder.name = e.target.value;

      // 创建新文件夹
      const newFolder = await indexedDBManager.createFolder({
        uid: currentUser.uid,
        parentId: 0, // 桌面文件夹
        name: e.target.value,
        x: folder.x,
        y: folder.y,
        icon: folder.iconUrl || 'folder.png',
        isStatic: false
      });

      // 更新本地状态
      dispatch({
        type: "setState",
        payload: {
          folderData: [...folderData, newFolder],
          isNewBuild: false,
          isRenameId: [],
        },
      });
    } catch (error) {
      message.error("创建文件夹失败");
      console.error(error);
    }
  };

  const optionFile = (e) => {
    if (isNewBuild) {
      dispatch({
        type: "setState",
        payload: {
          isNewBuild: false,
          isRenameId: [],
        },
      });
      addFilehandle(e);
    } else if (isRename) {
      dispatch({
        type: "setState",
        payload: {
          isRenameId: [],
        },
      });
      updateFileName(e);
    }
  };

  const _handlderContextMenu = (e) => {
    e.stopPropagation(); // 防止事件冒泡
    e.preventDefault(); // 防止默认事件
    dispatch({
      type: "setState",
      payload: {
        deskMenuVisible: false,
        folderMenuVisible: true,
        barMenuVisable: false,
        folderMenuX: e.clientX,
        folderMenuY: e.clientY,
        folderMenuSelectNum: fid,
        isStatic,
        fileIconType: iconType,
        contextMeunPathData: [
          { uid, fid, x, y, name, iconType, iconUrl, fatherNode },
        ],
        contextMeunIframe:
          iconType === 3
            ? {
              fid,
              x: 0,
              y: 0,
              name,
              iconType,
              iframeUrl,
              iframeColor,
              iconUrl,
              width: 700,
              height: 330,
            }
            : {},
        selectFid: fid,
        explorerTitleName: name,
      },
    });
  };

  // 打开iframe
  const openIframe = () => {
    const isExeit = iframeList.find((item) => item.fid === fid);
    if (isExeit) return;
    let iframe = { fid, x: 0, y: 0, name, iconType, iframeUrl, iframeColor, iconUrl, width: 700, height: 330 };
    const barIndex = barIconData.findIndex((item) => item.fid === fid);
    if (barIndex === -1) {
      barIconData.push(iframe);
      sessionStorage.setItem(`${name + fid}`, JSON.stringify(iframe));
    }
    sessionStorage.setItem("barIconData", JSON.stringify(barIconData));
    iframeList.push(iframe);
    dispatch({
      type: "setState",
      payload: {
        iframeList,
        barIconData,
      },
    });
  };

  // 打开文件夹
  const openFolderHander = () => {
    let folder = {
      fid,
      name,
      iconType,
      iconUrl,
    };
    const folderIndex = barIconData.findIndex((item) => item.iconType === 0);
    if (folderIndex === -1) {
      barIconData.push(folder);
    } else {
      barIconData[folderIndex] = folder;
    }
    dispatch({
      type: "setState",
      payload: {
        isFolderVisiable: true,
        deskMenuVisible: false,
        folderMenuVisible: false,
        barMenuVisable: false,
        selectFid: fid,
        explorerTitleName: name,
        filePathData: [{ uid, fid, x, y, name, iconType, iconUrl, fatherNode }],
        barIconData,
      },
    });
  };

  const openHandler = () => {
    console.log("iconType", typeof iconType);
    switch (iconType) {
      case FOLDER_ICON_TYPE: // 打开文件夹
        openFolderHander();
        break;
      case BLOG_ICON_TYPE: // 打开markdown文件
        navigate("/blog", { state: { fid, uid, name } });
        break;
      case TEXT_ICON_TYPE: // 打开回收站
        console.log("打开文本");
        break;
      case IFRAME_ICON_TYPE:
        openIframe();
        break;
      default:
        break;
    }
  };

  const rows = useMemo(() => {
    return getRows(filename);
  }, [filename]);

  return (
    <FolderS
      ref={folderNode}
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      position={{ left: x, top: y, zIndex }}
      onClick={folderHandler}
      onDoubleClick={openHandler}
      isFocus={isFocus}
      isHover={isHover}
      onMouseOver={onMouseOver}
      onMouseOut={onMouseOut}
      onContextMenu={_handlderContextMenu}
    >
      <FolderS.icon src={iconUrl} draggable={true} title={filename} alt={filename} />
      {!isRename && <FolderName isFocus={isFocus}>{filename}</FolderName>}
      {isRename && (
        <FodlerInput
          ref={textareaNode}
          value={filename}
          rows={rows} // 控制行数
          onChange={changeValueName}
          onBlur={optionFile}
          maxLength="144"
        />
      )}
    </FolderS>
  );
};

export default Folder;
